"""
@Project ：PythonInterfaceFrame
@File    ：SendMessageUtil.py
@IDE     ：PyCharm
@Author  ：ceiling
@Date    ：2025/4/25 20:18
"""
import requests


class SendMessageUtil:
    """
    发送飞书测试数据结果统计
    """

    @staticmethod
    def send_feishu_results_msg(webhook, desc, cases_total, cases_success_total, cases_fail_total,
                                cases_error_total, cases_skipped_total, cases_time_total, failed_cases_list,
                                cases_report_address):
        elements = [
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": f"**📋 {desc}**"
                }
            },
            {
                "tag": "hr"
            },
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": (
                        f"🔢 **用例总数**：{cases_total}\n"
                        f"✅ **成功用例数**：{cases_success_total}\n"
                        f"💥 **失败用例数**：{cases_fail_total}\n"
                        f"❌ **错误用例数**：{cases_error_total}\n"
                        f"⏭️ **跳过用例数**：{cases_skipped_total}\n"
                        f"⏱️ **运行耗时**：{cases_time_total} 秒"
                    )
                }
            }
        ]

        # 有失败用例时，添加失败用例列表
        if failed_cases_list and failed_cases_list != "无":
            # 拼接所有失败用例
            failed_cases_md = "\n".join([f"- {case}" for case in failed_cases_list])

            elements.append({
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": f"**❗失败用例列表：**\n{failed_cases_md}"
                }
            })

        # 添加查看报告按钮
        elements.append({
            "tag": "action",
            "actions": [
                {
                    "tag": "button",
                    "text": {
                        "tag": "plain_text",
                        "content": "📄 查看测试报告"
                    },
                    "type": "primary",
                    "url": cases_report_address
                }
            ]
        })

        # 创建卡片消息
        card_payload = {
            "msg_type": "interactive",
            "card": {
                "config": {
                    "wide_screen_mode": True
                },
                "header": {
                    "title": {
                        "tag": "plain_text",
                        "content": "自动化测试结果"
                    }
                },
                "elements": elements
            }
        }

        # 发送请求
        response = requests.post(url=webhook, json=card_payload)

        print("正在发送飞书测试结果卡片消息, 结果如下:")
        print(response.json())

    """
    通知飞书人员（@某人或@所有人）
    飞书人名为唯一标识 例如：@张三
    """

    @staticmethod
    def send_feishu_notifying_officer(webhook, notifying_officer="@all"):
        """
        :param webhook: 飞书群机器人 webhook 地址
        :param notifying_officer: 通知人员手机号列表 ["185xxxx", "@all"]
        :return:
        """
        mention_text = ""
        for officer in notifying_officer:
            if officer == "@all":
                mention_text += "<at user_id=\"all\">所有人</at> "
            else:
                mention_text += f"<at user_id=\"{officer}\">{officer}</at> "

        body = {
            "msg_type": "text",
            "content": {
                "text": f"{mention_text}\n请注意查看测试结果。"
            }
        }
        response = requests.post(url=webhook, json=body)
        print("正在通知飞书人员, 结果如下:")
        print(response.json())

    @staticmethod
    def send_work_wechat_results_msg(webhook, desc, cases_total, cases_success_total, cases_fail_total,
                                     cases_error_total, cases_skipped_total, cases_time_total, failed_cases_list,
                                     cases_report_address):

        markdown_content = (
            f"**📋 {desc}**\n"
            f"> 🔢 用例总数：**{cases_total}**\n"
            f"> ✅ 成功用例数：**{cases_success_total}**\n"
            f"> 💥 失败用例数：**{cases_fail_total}**\n"
            f"> ❌ 错误用例数：**{cases_error_total}**\n"
            f"> ⏭️ 跳过用例数：**{cases_skipped_total}**\n"
            f"> ⏱️ 运行耗时：**{cases_time_total} 秒**\n"
        )
        if failed_cases_list and failed_cases_list != "无":
            failed_cases_md = "\n".join([f"- {case}" for case in failed_cases_list])
            markdown_content += f"\n**❗失败用例列表：**\n{failed_cases_md}"

        markdown_content += f"\n\n[📄 点击查看测试报告]({cases_report_address})"

        body = {
            "msgtype": "markdown",
            "markdown": {
                "content": markdown_content
            }
        }
        response = requests.post(url=webhook, json=body)
        print("正在发送企业微信测试结果卡片消息, 结果如下:")
        print(response.json())

    """
    通知企业微信人员
    """

    @staticmethod
    def send_work_wechat_notifying_officer(webhook, notifying_officer="@all"):
        """
        :param webhook: 群机器人 webhook 地址
        :param notifying_officer: 通知人员 list列表 例如 ["150xxx", "@all"] 其中手机号为唯一标识 @all 为艾特全体人员
        :return:
        """
        body = {
            "msgtype": "text",
            "text": {
                "mentioned_mobile_list": notifying_officer
            }
        }
        response = requests.post(url=webhook, json=body)
        print("正在通知企业微信人员, 结果如下:")
        print(response.json())

    """
    发送测试结果统计信息到钉钉群机器人
    """
    @staticmethod
    def send_ding_talk_results_msg(webhook, desc, cases_total, cases_success_total, cases_fail_total,
                                   cases_error_total, cases_skipped_total, cases_time_total,
                                   failed_cases_list, cases_report_address):
        markdown_text = (
            f"## 📋 {desc}\n\n"
            f"🔢 **用例总数**：{cases_total}\n\n"
            f"✅ **成功用例数**：{cases_success_total}\n\n"
            f"💥 **失败用例数**：{cases_fail_total}\n\n"
            f"❌ **错误用例数**：{cases_error_total}\n\n"
            f"⏭️ **跳过用例数**：{cases_skipped_total}\n\n"
            f"⏱️ **运行耗时**：{cases_time_total} 秒\n\n"
        )

        if failed_cases_list and failed_cases_list != "无":
            failed_cases_md = "\n".join([f"- {case}" for case in failed_cases_list])
            markdown_text += f"### ❗失败用例列表：\n{failed_cases_md}\n\n"

        markdown_text += f"[📄 查看测试报告]({cases_report_address})"

        body = {
            "msgtype": "markdown",
            "markdown": {
                "title": "自动化测试结果",
                "text": markdown_text
            }
        }

        response = requests.post(url=webhook, json=body)
        print("正在发送钉钉测试结果Markdown消息, 结果如下:")
        print(response.json())

    """
    通知钉钉指定人员（@某人或@所有人）手机号为 唯一标识
    """
    @staticmethod
    def send_ding_talk_notifying_officer(webhook, notifying_officer=["@all"]):
        """
        发送钉钉通知
        :param webhook: 钉钉群机器人 webhook 地址
        :param notifying_officer: 通知人员手机号列表，如 ["150xxxx", "@all"]
        """
        at_mobiles = [user for user in notifying_officer if user != "@all"]
        is_at_all = "@all" in notifying_officer

        data = {
            "msgtype": "text",
            "text": {
                "content": "请注意查看测试结果。" +
                           (" " + " ".join([f"@{user}" for user in at_mobiles]) if at_mobiles else "")

            },
            "at": {
                "atMobiles": at_mobiles,
                "isAtAll": is_at_all
            }
        }

        response = requests.post(url=webhook, json=data)
        print("正在通知钉钉人员, 结果如下:")
        print(response.json())
